package com.woniu.shop.task;

import com.woniu.constant.Constant;
import com.woniu.shop.utils.AliyunUploadUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @author Ma.Lei
 * @description
 * @date 2023/2/17 11:37
 */
@Configuration
@Slf4j
public class DeleteRedisImageTask {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

//    @Scheduled(cron = "50 * * * * ?")
    public void clearImageTask(){
        log.debug("===清除无效图片任务开始====");
        //获取集合差值
        Set<String> difference = stringRedisTemplate.opsForSet().difference(Constant.REDIS_ALL_UPLOAD_IMAGE, Constant.REDIS_DB_UPLOAD_IMAGE);
        // 遍历差值集合
        if (difference != null && difference.size() > 0){
            for (String fileName : difference) {
                AliyunUploadUtils.deleteFile(fileName);
                log.debug("===清除无效图片"+fileName+"====");
                //将删除的图片名称从all这集合中删除
                stringRedisTemplate.opsForSet().remove(Constant.REDIS_ALL_UPLOAD_IMAGE,fileName);
            }
        }
        log.debug("======清除无效图片定时任务结束=====");
    }
    //@Scheduled(cron = "0 0/2 * * * ?")
    public void clearImageSet(){
        log.debug("=====清除redis图片集合定时任务开始=====");
        //清空之前先执行一次清除无效图片的方法
        clearImageTask();
        //清空两个集合
        stringRedisTemplate.delete(Constant.REDIS_ALL_UPLOAD_IMAGE);
        stringRedisTemplate.delete(Constant.REDIS_DB_UPLOAD_IMAGE);
        log.debug("=======清除redis图片集合定时任务结束=====");
    }
}
